<template>
    <BPTable ref='tableRef' align='center' row-key='id' name-key='account' :columns='columns' :api='pageApi' :buttons='buttons'>
        <template #enable='{record}'>
            <a-tag v-if='record.enable' color='success'>{{$t('enable')}}</a-tag>
            <a-tag v-else>{{$t('disable')}}</a-tag>
        </template>

        <template #$action='{record}'>
            <BTextButton @click="resetPwd(record.id)">{{$t('resetPwd')}}</BTextButton>
        </template>
    </BPTable>
    
    <BDialog v-model:visible='visible' :title='dialogTitle' width='600px' :confirm='submit'>
        <BForm ref='formRef' :label-col='{span : 5}' :fields='formFields'></BForm>
    </BDialog>

</template>

<script lang='ts' setup>
    import { pageApi, deleteApi, saveApi, restpwdApi } from '@/api/system/Member'
    import { optionsApi as departmentOptionsApi} from '@/api/system/Department'
    import { listApi as roleListApi} from '@/api/system/Role'
    import { message, Modal } from 'ant-design-vue'
    import { ref } from 'vue'
    import { useI18nStore } from '@/store/i18n'
    import { useResourceStore } from '@/store/resource'
    import { NODE_TYPE } from '@/constant/alicloud'

    const i18n = useI18nStore()
    const resourceStore = useResourceStore()

    const visible = ref(false)

    const tableRef = ref()
    const formRef = ref()
    const dialogTitle = ref()

    const formFields:FormField[] = [
        {label : 'id', name : 'id', hidden : true},
        {label : i18n.t('name'), name : 'name', required : true, minlength : 4, maxlength : 30},
        {label : i18n.t('nodeType'), name : 'nodeType', type : 'select', required : true, options : NODE_TYPE, valueFormat : Number},
        {label : i18n.t('category'), name : 'category', maxlength : 20},
        {label : i18n.t('netType'), name : 'netType', type : 'select', options : NODE_TYPE, valueFormat : Number},
        {label : i18n.t('tel'), name : 'tel', type : 'text', maxlength : 11},
        {label : i18n.t('enable'), name : 'enable', type : 'switch'},
        {label : i18n.t('remark'), name : 'remark', type : 'textarea', maxlength : 100}
    ]

    const buttons = ref<SearchButton[]>([])

    if(resourceStore.hasPermission('system:member:add')) {
        buttons.value.push({
            button : 'add',
            func : () => {
                dialogTitle.value = i18n.t('add')
                formFields.forEach(field => {
                    delete field.defaultValue

                    if(field.name == 'account') {
                        field.attrs = null
                    }else if(field.name == 'password') {
                        field.hidden = false
                    } else if(field.name == 'enable') {
                        field.defaultValue = true
                    }else if(field.name == 'roles') {
                        field.defaultValue = []
                    }
                })
                
                visible.value = true
            }
        })
    }


    

    async function getDepartmentList() {
        // const res = await departmentOptionsApi()
        // if(res.data.length > 0) {
        //     return recursionFn(res.data, Math.min(...res.data.map(row => row.parentId)), 'id', 'parentId', 'children')
        // }
        return []
    }

    async function getRoleList() {
        const res = await roleListApi()
        return res.data
    }

    async function submit() {
        const formData = await formRef.value.validate()
        if(formData.ability === '') {
            formData.ability = 0
        }

        formData.status = Number(formData.status)
        if(formData.deptId === '') {
            formData.deptId = 0
        }

        if(formData.password === '') {
            delete formData.password
        }

        const res = await saveApi(formData)
        if(res.success) {
            visible.value = false
            message.success(i18n.t('saveSuccess'))
            tableRef.value.load()
        }else {
            Modal.error({
                title : res.msg
            })
        }
    }

    function resetPwd(id:number) {
        Modal.confirm({
            content : i18n.concat('confirm', 'resetPwd', 'doubtSymbol'),
            async onOk() {
                const res = await restpwdApi(id)
                if(res.success) {
                    message.success(i18n.t('operateSuccess'))
                }else {
                    Modal.error({
                        title : res.msg
                    })
                }
            }
        })
    }

    const columns = ref<Column[]>([
        {
            title : i18n.t('account'),
            dataIndex : 'account',
            align : 'center',
            inSearch : true,
        },

        {
            title : i18n.t('name'),
            dataIndex : 'name',
            align : 'center',
            inSearch : true,
        },

        {
            title : i18n.t('role'),
            dataIndex : 'role',
            align : 'center',
            customRender({ record }) {
                return record.roleNames ? record.roleNames.join(' ') : ''
            }
        },

        {
            title : i18n.t('tel'),
            dataIndex : 'tel',
            align : 'center',
        },

        // {
        //     title : i18n.t('dept'),
        //     dataIndex : 'deptName',
        //     align : 'center',
        //     inSearch : true,
        // },

        {
            title : i18n.t('enable'),
            dataIndex : 'enable',
            align : 'center',
        },

        {
            title : i18n.t('operation'),
            dataIndex : '$action',
            align : 'center',
            $edit : resourceStore.hasPermission('system:member:edit') ? (row) => {
                dialogTitle.value = i18n.t('edit')
                formFields.forEach(field => {
                    if(field.name === 'password') {
                        field.defaultValue = ''
                        field.hidden = true
                        return
                    }
                    
                    if(field.name === 'account'){
                        field.attrs = {
                            disabled : true
                        }
                    }

                    field.defaultValue = row[field.name]

                })
                visible.value = true
            } : undefined,

            $delete : resourceStore.hasPermission('system:member:delete') ? async (row) => {
                const res = await deleteApi(row.id)
                if(res.success) {
                    message.success(i18n.t('deleteSuccess'))
                    tableRef.value.load()
                }else {
                    message.error(res.msg)
                }
            } : undefined
        }
    ])
</script>

<style lang='scss' module>
    .username{
        display: inline-flex;
        align-items: center;
        gap: 10px;
    }
</style>